package tables;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import fj.data.Option;

import server.Initialize;
import server.db.StmtHelper;
import utils.Strings;
import ajaxmethods.SessionMethod;

public class LeadsTable extends SessionMethod {

	public static String url() {
		return Initialize.appURL()+"/ajaxCall.jsp?do="+LeadsTable.class.getCanonicalName();
	}
	private String size = "";

	@Override
	public void perform(HttpServletRequest request, HttpServletResponse response)
	{
		super.perform(request, response);
		//Get Leads
		if(global.isLoggedIn.f(request))
		{
			StmtHelper prep = StmtHelper.db("select * from leads where iduser = ").addVariable(this.global.getUser().id);
			if(request.getParameterMap().containsKey("formid"))
				prep.addSql(" and idforms=").addVariable(request.getParameter("formid"));
			try {
				List<Map<String,String>> leadsList = prep.collectIntoMaps.unsafeGet();
				if(leadsList!=null && leadsList.size()>0)
					size=String.valueOf(leadsList.size());
				else
					size = "0";
				
					StringBuffer sb = new StringBuffer();
					sb.append("<div id=\"leadsTable\">");
					sb.append("<div class=\"headerCols\">");
					sb.append("<div style=\"width:90px;\" class=\"col\">Lead Name</div>");
					sb.append("<div style=\"width:155px;\" class=\"col\">Email</div>");
					sb.append("<div style=\"width:125px;\" class=\"col\">Message</div>");
					sb.append("<div style=\"width:122px;\" class=\"col\">Add As Contact</div>");
					sb.append("<div style=\"width:30px;\" class=\"col\">Delete</div>");
					//close headerCols
					sb.append("</div><div class=\"verticalscroll\"><div class=\"items\"><div class=\"section\">");
				if(leadsList!=null)
				{
					for(int i = 0;i < leadsList.size(); i++)
					{
						if(i>0&&i%7==0)
							sb.append("</div><div class=\"section\">");
						Map<String,String> leadsMap = leadsList.get(i);
						sb.append("<div id=\""+leadsMap.get("idforms")+"\" class=\"row\"><div class=\"codecontent\" style=\"display:none;\"></div>");
						sb.append("<div style=\"width:90px;\" class=\"rowitem\">"+leadsMap.get("firstname")+" "+leadsMap.get("lastname")+"</div>");
						sb.append("<div style=\"width:155px;\" class=\"rowitem\"><a onclick=\"$.address.value('/email');\">"+Option.fromString(leadsMap.get("email")).orSome("")+"</a></div>");
						sb.append("<div style=\"width:121px;\" class=\"rowitem\">"+Strings.ellipsize(leadsMap.get("message"),25)+"</div>");
						sb.append("<div style=\"width:120px;\" class=\"rowitem\"><div extraheight=\"205\" class=\"codeBubble\" id=\"detailview\"><a id=\""+leadsMap.get("idforms")+"\" class=\"detailLink addbutton\">+</a></div></div>");
						sb.append("<div style=\"width:30px;\" class=\"rowitem\"><img extraheight=\"130\" class=\"delete\" src=\""+Initialize.appURL()+"/images/icons/delete.png\"/></div>");
						sb.append("</div>");
					}
				}	
					sb.append("</div>");
					//close leadsTable
					sb.append("</div></div></div>");
					
					sb.append(javascriptOut());
					if(leadsList!=null && leadsList.size()>0)
						data.put("hasALead", true);
					data.put("hasLead", sb.toString()).write(response.getWriter());
			
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else
			try {
				data.write(response.getWriter());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	private StringBuffer javascriptOut() {
		StringBuffer sb = new StringBuffer();
		sb.append("<script>");
		sb.append("$(document).ready(function() {" +
				"$('#scrollLeads .verticalscroll').scrollable({vertical:true,pagingtable:true,touch:false,tablesize:7,next:'#head #action .next',prev:'#head #action .prev'," +
				"onSeek:function(){" +
				"if(this.getIndex()==0)" +
				"	this.getItemWrap().css('top',0);" +
				"var size = this.getRowItems().size();\n" +
					"$('#action #start').html(parseInt(7*this.getIndex())+1);" +
					"$('#action #end').html(Math.min(size,parseInt(7*this.getIndex())+7));" +
					"$('#displaynumobjects #total').html(size);" +
					"if(size<=7)" +
					"	$('#action .next').addClass('disabled');" +
		" }}).data('scrollable').seekTo(0);" +
		
		"if($('#scrollLeads .verticalscroll').data('scrollable').getRowItems().size()==0) {" +
		"	$('#noobjectsfound').show().next().hide();" +
		"}" +
		"$('#action #displaynumobjects #total').html("+size+");" +
		"$('.editformname').unbind('click').click(function(){var elem = $(this);$('.rowitem .textbox').hide().prev().show();elem.siblings('.textbox').show().find('input').val(elem.parent().find('a.editformname').hide().html()).select(); });" +
		"$('button[name=\"submit\"],button[name=\"cancel\"]').unbind('click').click(function(){\n" +
		"var button=$(this);" +
		"if(button.attr('name')=='submit') {" +
		"	var newtitle = $(this).prev().val();" +
		"	$.post('"+UpdateForm.url()+"',{idform:button.parent().parent().parent().attr('id'),formname:newtitle}," +
				"function(data){" +
				"button.parent().prev().html(newtitle).show();" +
				"$('.rowitem .textbox').hide();" +
				"});" +
		"}" +
		"else {" +
		"	$('.rowitem .textbox').hide();" +
		"	button.parent().prev().show();" +
		"}});" +
		"$('#leadsTable').bubble({popupItemSelector:'#leadsTable .codeBubble',bubbleselector:'leadbubble'," +
		"autoclose:true,onOpen:function(){" +
		"	$('textarea#formCode').text($('#'+$(this).find('a').attr('id')+' .codecontent').html());" +
		"}}).data('leadbubble').resize(240,155).setBody('<textarea class=\"esotextarea\" style=\"height:80px;width:212px;\" id=\"formCode\" ></textarea><p>Embed this code in your website to generate leads</p>');" +
		"$('#leadsTable').bubble({popupItemSelector:'#leadsTable img.delete',bubbleselector:'deletebubble',autoclose:true," +
		"onOpen:function() {" +
		"		}}).data('deletebubble').resize(200,110).setBody('<p>Are you sure you want to permanently remove this lead?</p>" +
		"<button id=\"deleteform\" onclick=\"deleteForm($(this));\" class=\"esobutton\">Yes</button><button onclick=\"closeDeleteBubble();\" class=\"esobutton\">No</button>');" +
		"$('.rowitem .delete').click(function(){var deleteImg = $(this);$('button#deleteform').attr('idform',deleteImg.closest('.row').attr('id'));});" +
		"$('#leadsTable .verticalscroll .row').hover(function(){$('#noscrollsidepanel .leadsmall').html($(this).find('.codecontent').html());},function(){$('#noscrollsidepanel .leadsmall').children().remove();});" +
		"});");
		sb.append("function deleteForm(button) {\n" +
				"var id = button.attr('idform');" +
				"	$.post('"+DeleteForm.url()+"',{idform:id},"+
				"function(data){" +
				"var scrollAPI = $('#scrollLeads .verticalscroll').data('scrollable');" +
				"$('#leadsTable .row#'+id).slideToggle(function(){scrollAPI.deleteItem(this);});\n" +
				"$('#leadsTable').data('deletebubble').close();" +
				"var total = $('#head #action #displaynumobjects #total');total.html(total.html()-1); " +
				"if(parseInt(total.html())==0) " +
				"	$('#noobjectsfound').show().next().hide();" +
				"var end = $('#displaynumobjects #end'); if(parseInt(end.html())>parseInt(total.html())) end.html(total.html());" +
				"var start = $('#displaynumobjects #start'); " +
				"if(parseInt(start.html()) > parseInt(end.html())) {start.html(end.html());}" +
				"});" +
				"}");
		sb.append("function closeDeleteBubble() {$('#leadsTable').data('deletebubble').close();}");
		sb.append("</script>");
		return sb;
	}

}
